/**
 * 初始化流转环节列表
 * 
 * @param {}
 *            fid 工作流程ID
 */
function stepList(gid, gname) {
	// create the Data Store
	var store = new Ext.data.JsonStore({
				root : 'stepList',
				totalProperty : 'totalCount',
				remoteSort : true,

				fields : ['PAGINATION_NUMBER', 'S_ID', 'S_NAME', 'S_NO',
						'S_TYPE', 'S_TYPENAME', 'S_INNER', 'S_INNERNAME',
						'S_STATUS', 'CG_ID'],

				proxy : new Ext.data.ScriptTagProxy({
							url : context
									+ '/system/flowmanage.do?method=steplist&gid='
									+ gid
						})
			});

	store.setDefaultSort('S_ID', 'asc');

	var grid = new Ext.grid.GridPanel({
				id : 'steplist',
				border : false,
				store : store,
				trackMouseOver : false,
				disableSelection : true,
				loadMask : true,

				// grid columns
				columns : [new Ext.grid.RowNumberer(), {
							id : 'fname',
							header : "环节名称",
							dataIndex : 'S_NAME',
							align : 'center',
							sortable : true,
							width : 200,
							renderer : renderStepName
						}, {
							header : "环节编号",
							dataIndex : 'S_NO',
							sortable : true,
							width : 50,
							align : 'center'
						}, {
							header : "环节类型",
							dataIndex : 'S_TYPENAME',
							align : 'center',
							width : 150
						}, {
							header : "分支环节",
							dataIndex : 'S_INNERNAME',
							width : 100
						}, {
							header : "设置",
							dataIndex : 'PAGINATION_NUMBER',
							width : 150,
							renderer : renderStepSet
						}],

				// customize view config
				viewConfig : {
					forceFit : true,
					enableRowBody : true,
					showPreview : false
				},

				bbar : new Ext.PagingToolbar({
							pageSize : 25,
							store : store,
							displayInfo : true,
							displayInfo : true,
							displayMsg : '总记录数 {0} - {1} of {2}',
							emptyMsg : "没有数据"
						})
			});

	store.on('load', function(s, records) {
		var girdcount = 0;
		s.each(function(r) {
			if (r.get('S_STATUS') == 0) {
				// grid.getView().getRow(girdcount).style.backgroundColor =
				// '#fffff0';
			} else if (r.get('S_STATUS') == -1) {
				grid.getView().getRow(girdcount).style.backgroundColor = '#ffff00';
				grid.getView().getRow(girdcount).setAttribute("title", "已删除节点");
			}
			girdcount = girdcount + 1;
		});
	});

	// trigger the data store load
	store.load({
				params : {
					start : 0,
					limit : 25
				}
			});

	var win = new Ext.Window({
				id : 'stepListWin',
				renderTo : Ext.getBody(),
				layout : 'fit',
				width : 800,
				height : 500,
				title : gname,
				plain : true,
				modal : true,
				maximizable : true,
				items : [grid]
			});

	win.show(this);
}

/**
 * render 环节编辑
 * 
 * @param {}
 *            value
 * @param {}
 *            p
 * @param {}
 *            record
 * @return {}
 */
function renderStepName(value, p, record) {
	var str = String
			.format(
					'<b><a href="javascript:void(0);" onclick="javascript:editStep(\'{1}\');">{0}</a></b>',
					value, record.data.S_ID);
	return str;
}

/**
 * render 环节设置
 * 
 * @param {}
 *            value
 * @param {}
 *            p
 * @param {}
 *            r
 * @return {}
 */
function renderStepSet(value, p, r) {
	var str = '<a href="javascript:void(0);" onclick="javascript:deleteStep(\'{0}\',\'{1}\');">删除</a>';

	if (r.data.S_STATUS == -1) {
		str += '&nbsp;<a href="javascript:void(0);" onclick="javascript:validStep(\'{0}\',\'{1}\');">恢复</a>';
	}

	if (r.data.S_TYPE != -1) {
		str += '&nbsp;<a title="设置当前环节操作表单项权限" href="javascript:void(0);" onclick="javascript:handlingStep(\'{2}\',\'{0}\',\'{1}\');">表单项处理</a>';
		str += '&nbsp;<a title="当前环节流向环节列表" href="javascript:void(0);" onclick="javascript:viewTrend(\'{2}\',\'{0}\',\'{1}\');">流向环节</a>';
	}
	str = String.format(str, r.data.S_ID, r.data.S_NAME, r.data.CG_ID);
	return str;
};

/**
 * render 环节类型
 * 
 * @param {}
 *            value
 * @param {}
 *            p
 * @param {}
 *            record
 * @return {}
 */
function renderStepType(value, p, record) {
	var tp = "";
	if (value == "-1") {
		tp = "结束环节";
	} else if (value == "0") {
		tp = "开始环节";
	} else if (value == "1") {
		tp = "办理环节";
	} else if (value == "2") {
		tp = "传阅环节";
	} else if (value == "3") {
		tp = "编号环节";
	}
	return tp;
}

/**
 * render 环节inner
 * 
 * @param {}
 *            value
 * @param {}
 *            p
 * @param {}
 *            record
 * @return {}
 */
function renderStepInner(value, p, record) {
	var inner = "";
	if (value == "0") {
		inner = "否";
	} else {
		inner = "是";
	}

	return inner;
}

/**
 * 删除流程环节
 * @param {} id 环节id
 */
function deleteStep(id) {
	Ext.MessageBox.confirm('提示', '确定删除流转环节？', function(btn) {
				if (btn == 'yes') {
					var url = context
							+ '/system/flowmanage.do?method=deletestep';

					Ext.Ajax.request({
								// 请求地址
								url : url,
								params : {
									id : id
								},
								scriptTag : true,
								// 成功时回调
								success : function(response, options) {
									var json = response.responseText;
									var o = Ext.util.JSON.decode(json);

									if (o.success) {
										Ext.Msg.alert('提示', '成功删除流转环节');
									} else {
										Ext.Msg.alert('错误提示',
												'删除流转环节失败,请确认该环节是否已在使用中');
									}
								},
								failure : function(response, options) {
									Ext.Msg
											.alert('错误提示',
													response.responseText);
								}

							});
				}
			});
}

/**
 * 设置环节处理表单项权限
 * 
 * @param {}
 *            gid
 * @param {}
 *            sid
 * @param {}
 *            name
 */
function handlingStep(gid, sid, name) {
	var url = context + '/system/flowmanage.do?method=editstate&sid=' + sid
			+ '&gid=' + gid

	Ext.Ajax.request({
		// 请求地址
		url : url,
		scriptTag : true,
		// 成功时回调
		success : function(response, options) {
			var json = response.responseText;
			var o = Ext.util.JSON.decode(json);

			if (o.success) {
				var tables = new Array();

				var win = new Ext.Window({
							renderTo : Ext.getBody(),
							layout : 'accordion',
							split : true,
							title : '{' + name + '}环节_表单项操作权限设置',
							width : 700,
							height : 500,
							plain : true,
							modal : true,
							maximizable : false,
							buttons : [{
										text : '保 存',
										handler : function() {
											updateHandleSet(win, tables, sid);
										}
									}, {
										text : '关 闭',
										handler : function() {
											win.close();
											win = null;
										}
									}]

						});

				var idx = 0;

				Ext.each(o.handleList, function(item) {
					var store = new Ext.data.Store({
								reader : new Ext.data.JsonReader({
											root : 'resultList',
											fields : ['PAGINATION_NUMBER',
													'H_ID', 'S_ID', 'OBJ_ITEM',
													'OBJ_ITEMNAME', 'H_TYPE',
													'OBJ_TABLE',
													'OBJ_TABLENAME',
													'OBJ_TABLEHANDLE']
										})
							});

					var grid = null;

					if (item.tableHandle == 1) {
						grid = new Ext.grid.EditorGridPanel({
									title : item.tableMemo + ' ['
											+ item.tableName + ']',
									border : false,
									store : store,
									trackMouseOver : false,
									disableSelection : true,
									loadMask : true,

									// grid columns
									columns : [new Ext.grid.RowNumberer(), {
												header : "表单项名称",
												dataIndex : 'OBJ_ITEMNAME',
												width : 150
											}, {
												header : '操作权限',
												width : 100,
												sortable : false,
												editor : getWBComboStore(
														'purview', '',
														'purview_' + idx, '',
														null, null, '0'),
												dataIndex : 'H_TYPE'
											}, {
												header : "表单项字段名称",
												dataIndex : 'OBJ_ITEM',
												width : 100
											}, {
												header : "字段所属表",
												dataIndex : 'OBJ_TABLE',
												width : 100
											}, {
												header : "表数据处理类型",
												dataIndex : 'OBJ_TABLEHANDLE',
												align : 'center',
												width : 100
											}],
									tbar : new Ext.Toolbar({
												autoWidth : true,
												autoShow : true,
												items : []
											}),

									// customize view config
									viewConfig : {
										forceFit : true,
										enableRowBody : true,
										showPreview : false
									}
								});

						store.loadData(item.columnList);

						var tb = grid.getTopToolbar();

						var insertChkId = 'insertChk_' + item.tableName;

						var delChkId = 'delChk_' + item.tableName;

						tb.add('添加数据:')
						tb.add(new Ext.form.Checkbox({
									id : insertChkId,
									checked : item.tableAdd == 1,
									inputValue : item.tableAddId
								}));
						tb.add('-');
						tb.add('删除数据:')
						tb.add(new Ext.form.Checkbox({
									id : delChkId,
									checked : item.tableDel == 1,
									inputValue : item.tableDelId
								}));

						tables.push([grid, item.tableHandle, insertChkId,
								delChkId, item.tableName]);
					} else {
						grid = new Ext.grid.EditorGridPanel({
							title : item.tableMemo + ' [' + item.tableName
									+ ']',
							border : false,
							store : store,
							trackMouseOver : false,
							disableSelection : true,
							loadMask : true,

							// grid columns
							columns : [new Ext.grid.RowNumberer(), {
										header : "表单项名称",
										dataIndex : 'OBJ_ITEMNAME',
										width : 150
									}, {
										header : '操作权限',
										width : 100,
										sortable : false,
										editor : getWBComboStore('purview', '',
												'purview_', '', null, null, '0'),
										dataIndex : 'H_TYPE'
									}, {
										header : "表单项字段名称",
										dataIndex : 'OBJ_ITEM',
										width : 100
									}, {
										header : "字段所属表",
										dataIndex : 'OBJ_TABLE',
										width : 100
									}, {
										header : "表数据处理类型",
										dataIndex : 'OBJ_TABLEHANDLE',
										align : 'center',
										width : 100
									}],

							// customize view config
							viewConfig : {
								forceFit : true,
								enableRowBody : true,
								showPreview : false
							}
						});

						store.loadData(item.columnList);

						tables.push([grid, item.tableHandle]);
					}

					idx++;

					/*
					 * alert(item.tableName); alert(item.tableMemo);
					 * alert(item.tableHandle); alert(item.columnList.length);
					 */

					/*
					 * var accordion = new Ext.Panel({ border : false, split :
					 * true, layout : 'accordion', items : [grid] });
					 */

					win.items.add(grid);
					win.doLayout();
				});

				win.show(this);
			} else {
				Ext.Msg.alert('错误提示', '流转对象不包含任何表单项,无法进行权限设置');
			}
		},
		failure : function(response, options) {
			Ext.Msg.alert('错误提示', response.responseText);
		}
	});
}

/**
 * 编辑环节表单项操作权限
 * 
 * @param {}
 *            win
 * @param {}
 *            tables
 * @param {}
 *            sid
 */
function updateHandleSet(win, tables, sid) {
	var params;

	var countName = 0;
	var countNameStr = '';

	if (tables.length > 0) {
		params = '({'
		/* 关联表设置 */
		for (var i = 0; i < tables.length; i++) {
			var grid = tables[i][0];
			var handle = tables[i][1];

			var total = grid.getStore().getCount();

			if (handle == 0) {
				for (var j = 0; j < total; j++) {
					// 每行records对象
					var record = grid.getStore().getAt(j);

					params += 'hid_' + countName + ' : "' + record.data.H_ID
							+ '",';

					params += 'htype_' + countName + ' : "'
							+ record.data.H_TYPE + '",';

					params += 'oitem_' + countName + ' : "'
							+ record.data.OBJ_ITEM + '",';

					params += 'sid_' + countName + ' : "' + record.data.S_ID
							+ '",';

					params += 'otable_' + countName + ' : "'
							+ record.data.OBJ_TABLE + '",';

					countName++;
				}
			} else if (handle == 1) {
				var insertChkId = tables[i][2];
				var delChkId = tables[i][3];
				var tableName = tables[i][4];

				if (Ext.getCmp(insertChkId) && Ext.getCmp(insertChkId).checked) {
					params += 'hid_' + countName + ' : "'
							+ Ext.get(insertChkId).dom.value + '",';

					params += 'htype_' + countName + ' : "'
							+ (Ext.getCmp(insertChkId).checked ? '1' : '0')
							+ '",';

					params += 'oitem_' + countName + ' : "MADDTYPE",';

					params += 'sid_' + countName + ' : "' + sid + '",';

					params += 'otable_' + countName + ' : "' + tableName + '",';

					countName++;
				}

				if (Ext.getCmp(delChkId) && Ext.getCmp(delChkId).checked) {
					params += 'hid_' + countName + ' : "'
							+ Ext.get(delChkId).dom.value + '",';

					params += 'htype_' + countName + ' : "'
							+ (Ext.getCmp(delChkId).checked ? '1' : '0') + '",';

					params += 'oitem_' + countName + ' : "MDELTYPE",';

					params += 'sid_' + countName + ' : "' + sid + '",';

					params += 'otable_' + countName + ' : "' + tableName + '",';

					countName++;
				}

				for (var j = 0; j < total; j++) {
					// 每行records对象
					var record = grid.getStore().getAt(j);

					params += 'hid_' + countName + ' : "' + record.data.H_ID
							+ '",';

					params += 'htype_' + countName + ' : "'
							+ record.data.H_TYPE + '",';

					params += 'oitem_' + countName + ' : "'
							+ record.data.OBJ_ITEM + '",';

					params += 'sid_' + countName + ' : "' + record.data.S_ID
							+ '",';

					params += 'otable_' + countName + ' : "'
							+ record.data.OBJ_TABLE + '",';

					countName++;
				}
			}

		}

		for (var i = 0; i < countName; i++) {
			if (i == countName - 1) {
				countNameStr += i;
			} else {
				countNameStr += i + ',';
			}
		}

		params += 'countName : "' + countNameStr + '"';

		params += '})';
	}

	if (params == null) {
		Ext.Msg.alert('提示', '请选择设置操作权限');
	} else {
		Ext.MessageBox.wait('提交保存过程中...');

		Ext.Ajax.request({
					url : context + '/system/flowmanage.do?method=updatestate',
					method : 'POST',
					params : eval(params),
					scope : this,
					success : function(response) {
						var o = Ext.util.JSON.decode(response.responseText);
						if (o.success) {
							Ext.MessageBox.hide();

							Ext.Msg.alert('提示', '表单操作权限设置成功');

							win.close();
							win = null;
						} else {
							Ext.MessageBox.hide();

							Ext.Msg.alert('提示', '表单操作权限设置失败');
						}
					},
					failure : function(response) {
						Ext.MessageBox.hide();
						Ext.MessageBox.show({
									title : '提示信息',
									msg : response.responseText,
									icon : Ext.MessageBox.ERROR
								});

					}

				});
	}
}

function viewTrend(gid, sid, name) {
	var store = new Ext.data.JsonStore({
				root : 'stepList',
				totalProperty : 'totalCount',
				remoteSort : true,

				fields : ['PAGINATION_NUMBER', 'S_ID', 'S_NAME', 'S_NO',
						'S_TYPE', 'S_TYPENAME', 'S_INNER', 'S_INNERNAME',
						'S_STATUS', 'CG_ID'],

				proxy : new Ext.data.ScriptTagProxy({
							url : context
									+ '/system/flowmanage.do?method=trendlist&sid='
									+ sid
						})
			});

	store.setDefaultSort('S_ID', 'asc');

	var grid = new Ext.grid.GridPanel({
				id : 'steplist',
				border : false,
				store : store,
				trackMouseOver : false,
				disableSelection : true,
				loadMask : true,

				// grid columns
				columns : [new Ext.grid.RowNumberer(), {
							id : 'fname',
							header : "环节名称",
							dataIndex : 'S_NAME',
							align : 'center',
							width : 200
						}, {
							header : "环节类型",
							dataIndex : 'S_TYPENAME',
							align : 'center',
							width : 150
						}, {
							header : "分支环节",
							dataIndex : 'S_INNERNAME',
							width : 100
						}],

				// customize view config
				viewConfig : {
					forceFit : true,
					enableRowBody : true,
					showPreview : false
				}
			});

	// trigger the data store load
	store.load({
				params : {
					start : 0,
					limit : 25
				}
			});

	var win = new Ext.Window({
				renderTo : Ext.getBody(),
				layout : 'fit',
				width : 500,
				height : 400,
				title : '{' + name + '}环节_流向环节列表',
				plain : true,
				modal : true,
				maximizable : true,
				items : [grid]
			});

	win.show(this);
}